from rest_framework import serializers
from .models import OAuthQQUser
from django_redis import get_redis_connection
from users.models import User


# serializers.ModelSerializer  校验的参数不在模型中,所以不使用ModelSerializer
# serializers.Serializer
class QQTokenSerializer(serializers.Serializer):
    """
    1.当用户点击保存的时候,需要把access_token(openid),手机号,密码,短息验证码,使用post方式提交过来
    2.access_token,短信验证码需要进行校验
    3.需要将user和openid保存入库
    """""
    # 完成字段
    access_token = serializers.CharField(label='操作token')
    mobile = serializers.RegexField(label='手机号', regex=r'^1[345789]\d{9}$')
    password = serializers.CharField(label='密码', max_length=20, min_length=8)
    sms_code = serializers.CharField(label='短信验证码', max_length=6, min_length=6)

    # 完成校验
    def validate(self, attrs):

        # 1.access_token
        access_token = attrs.get('access_token')
        openid = OAuthQQUser.openid_by_token(access_token)
        if not openid:
            raise serializers.ValidationError('openid错误')

        # 把openid放到attrs中,验证没有问题之后,attrs其实就是validated_data
        attrs['openid'] = openid

        # 2.短信验证码
        # 短信验证码
        sms_code = attrs.get('sms_code')
        mobile = attrs.get('mobile')
        # 连接redis
        redis_conn = get_redis_connection('code')
        # 获取redis中保存的短信验证码
        redis_code = redis_conn.get('sms_%s' % mobile)
        # 判断短信验证码是否过期
        if not redis_code:
            raise serializers.ValidationError('短信验证码已过期')
        # 短信验证码是否一致
        if redis_code.decode() != sms_code:
            raise serializers.ValidationError('短信验证码不一致')

        # 3.根据手机号判断用户是否注册过
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            # 不存在
            # 创建一个
            pass
        else:
            # 存在
            # 绑定
            # 校验密码是否正确
            if not user.check_password(attrs['password']):
                raise serializers.ValidationError('您输入的密码不正确')
            attrs['user'] = user

        return attrs

    def create(self, validated_data):

        # 需要user和openid
        user = validated_data.get('user')

        if not user:
            # 创建一个用户
            user = User.objects.create(
                username=validated_data.get('mobile'),
                mobile=validated_data.get('mobile'),
                password=validated_data.get('password'),

            )
            user.set_password(validated_data.get('password'))
            user.save()

        OAuthQQUser.objects.create(
            user=user,
            openid=validated_data.get('openid')
        )

        return user